#include "board.h"
#include "uart.h"
#include "rtc.h"
#include "lfs_fun.h"
#include "w25qxx.h"
#include "sdram.h"
#include "terminal.h"
uint8_t uartShareBuffer[UART_SHARE_BUFFER_SIZE];
void Peripherals_Init(void) {
	USART1_Init(115200);
	printf("Peripherals Init\n");
	RTC_Init();
	W25QXX_Init();
	SDRAM_Init();
}

void Application_Init(void) {
	LFS_Init();
	Terminal_Init();
}
#define CALCULATION_PERIOD	1000
TaskHandle_t xIdleHandle = NULL;
TickType_t osCPU_IdleStartTime, osCPU_IdleSpentTime, osCPU_TotalIdleTime;
uint16_t osCPU_Usage;

uint16_t osGetCPUUsage(void)
{
	return osCPU_Usage;
}

void vApplicationIdleHook(void) {
	if(xIdleHandle == NULL) {
		xIdleHandle = xTaskGetCurrentTaskHandle();
	}	
}

void vApplicationTickHook (void)
{
	static int tick = 0;
	if(tick ++ >CALCULATION_PERIOD)
	{
		tick = 0;

		if(osCPU_TotalIdleTime> 1000)
		{
			osCPU_TotalIdleTime =1000;
		}
		osCPU_Usage = (100 -(osCPU_TotalIdleTime * 100) / CALCULATION_PERIOD);
		osCPU_TotalIdleTime =0;
	}
}

void StartIdleMonitor(void)
{
	if( xTaskGetCurrentTaskHandle() ==xIdleHandle )
	{
		osCPU_IdleStartTime =xTaskGetTickCountFromISR();
	}
}

void EndIdleMonitor(void)
{
  if( xTaskGetCurrentTaskHandle() ==xIdleHandle )
  {
    /* Store the handle to the idle task. */
    osCPU_IdleSpentTime =xTaskGetTickCountFromISR() - osCPU_IdleStartTime;
    osCPU_TotalIdleTime += osCPU_IdleSpentTime;
  }
}
